﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability_2203.Common.Domains;
using Traceability_2203.Common.Dtos;
using Traceability_2203.Common.Infrastructure.Interfaces;
using Traceability_2203.Enum;

namespace Traceability_2203.Bais.Api.Application.Commands.User
{
    public class UserUpdateHandler : IRequestHandler<UserUpdateCommand, Result>
    {
        private readonly IBaseRepository<Users> userRepository;
        private readonly ILogger<UserUpdateHandler> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userRepository"></param>
        /// <param name="logger"></param>
        public UserUpdateHandler(IBaseRepository<Users> userRepository,
                                 ILogger<UserUpdateHandler> logger)
        {
            this.userRepository = userRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(UserUpdateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result { Code = (int)CommonErrorCode.Updated };
            try
            {
                var user = await (await userRepository.GetAll()).FirstOrDefaultAsync(d => d.UserId == request.UserId);
                if (user != null)
                {
                    user.UserName = request.UserName;
                    user.UserPwd = request.UserPwd;
                }
                var res = await userRepository.Upd(user);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                }
            }
            catch (Exception ex)
            {
                logger.LogError("修改用户异常" + ex.Message);
            }
            return result;
        }
    }
}
